<template>
  <div class="crop-form-container">
    <!-- 产品基本信息 -->
    <div class="section-header">
      <h3>产品基本信息</h3>
      <el-button @click="$emit('back-to-list')" type="info" size="big">返回列表</el-button>
    </div>
    
    <div class="form-grid">
      <!-- 产品名称 -->
      <div class="form-item">
        <label class="form-label">产品名称<span class="required">*</span></label>
        <input v-model="productName" type="text" class="form-input" placeholder="请输入产品名称" />
      </div>

      <!-- 产品类别 -->
      <div class="form-item">
        <label class="form-label">产品类别<span class="required">*</span></label>
        <select v-model="productCategory" class="form-select">
          <option value="" disabled selected>请选择产品类别</option>
          <option value="蔬菜">蔬菜</option>
          <option value="水果">水果</option>
          <option value="粮食">粮食</option>
          <option value="经济作物">经济作物</option>
          <option value="其他">其他</option>
        </select>
      </div>

      <!-- 品种 -->
      <div class="form-item">
        <label class="form-label">品种<span class="required">*</span></label>
        <input v-model="variety" type="text" class="form-input" placeholder="请输入品种名称" />
      </div>

      <!-- 种植周期 -->
      <div class="form-item">
        <label class="form-label">种植周期<span class="required">*</span></label>
        <el-slider
          v-model="plantingCycle"
          :min="1"
          :max="365"
          show-input
          :format-tooltip="(val) => val + '天'"
        />
        <div class="planting-cycle-preview">
          当前选择种植周期: {{ plantingCycle }}天
        </div>
      </div>
    </div>

    <!-- 产品描述 -->
    <div class="form-item">
      <label class="form-label">产品描述</label>
      <textarea v-model="description" class="fixed-textarea" placeholder="请输入产品的详细描述，包括特点、用途等"></textarea>
    </div>

    <!-- 种植条件 -->
    <div class="section-header">
      <h3>种植条件</h3>
    </div>

    <div class="form-grid">
      <!-- 适宜土地类型 -->
      <div class="form-item">
        <label class="form-label">适宜土地类型<span class="required">*</span></label>
        <select v-model="suitableLand" class="form-select">
          <option value="" disabled selected>请选择土地类型</option>
          <option value="沙壤土">沙壤土</option>
          <option value="壤土">壤土</option>
          <option value="黏壤土">黏壤土</option>
          <option value="沙土">沙土</option>
          <option value="黑土">黑土</option>
          <option value="红壤">红壤</option>
        </select>
      </div>

      <!-- 适宜温度范围 -->
      <div class="form-item">
        <label class="form-label">适宜温度范围<span class="required">*</span></label>
        <el-slider
            v-model="suitableTemperature"
            range
            :min="-20"
            :max="50"
            show-input
            :format-tooltip="(val) => val + '°C'"
          />
          <div class="temperature-preview">
            当前选择温度范围: {{ suitableTemperature[0] }}°C - {{ suitableTemperature[1] }}°C
          </div>
      </div>

      <!-- 适宜种植月份 -->
      <div class="form-item">
        <label class="form-label">适宜种植月份<span class="required">*</span></label>
        <el-select v-model="suitableMonths" multiple placeholder="请选择月份" class="form-select">
          <el-option
            v-for="month in monthsOptions"
            :key="month.value"
            :label="month.label"
            :value="month.value"
          />
        </el-select>
        <div class="month-preview">
          当前选择月份: {{ suitableMonths.map(month => monthsOptions.find(opt => opt.value === month)?.label).join(',') }}
        </div>
      </div>

      <!-- 种植记录编号 -->
      <!-- <div class="form-item">
        <label class="form-label">种植记录编号</label>
        <input v-model="plantingRecordNumber" type="text" class="form-input" placeholder="请输入种植记录编号" />
      </div> -->
    </div>

    <!-- <div class="section-header">
      <h3>资质信息</h3>
    </div>

    <div class="form-grid">
      <div class="form-item">
        <label class="form-label">资质生效时间</label>
        <input v-model="qualificationEffectiveTime" type="date" class="form-input" />
      </div>

      <div class="form-item">
        <label class="form-label">资质过期时间</label>
        <input v-model="qualificationExpirationTime" type="date" class="form-input" />
      </div>
    </div> -->

    <!-- 注意事项 -->
    <div class="form-item">
      <label class="form-label">注意事项</label>
      <textarea v-model="precautions" class="fixed-textarea" placeholder="请输入种植和使用的注意事项"></textarea>
    </div>

    <!-- 操作按钮 -->
    <div class="form-footer">
      <el-button @click="savemsg" style="background-color: #2e7d32; border-color: #2e7d32;" type="primary" size="mini">保存并继续</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { addPermit } from '@/api/ncpsy/management/permit'
import { ElMessage, ElSlider, ElSelect, ElOption } from 'element-plus'
import useUserStore from '@/store/modules/user'

// 定义组件名称
const name = 'CropForm'
const userStore = useUserStore();
const userId = userStore.id;

const props = defineProps({
  initialPermitData: {
    type: Object,
    default: null
  }
});

// 产品基本信息
const productName = ref('')
const productCategory = ref('')
const variety = ref('')
const plantingCycle = ref(90)
const description = ref('')

// 种植条件
const suitableLand = ref('')
const suitableTemperature = ref([15, 25]) // 初始化为温度范围
const suitableMonths = ref([]) // 初始化为数组，用于多选
const plantingRecordNumber = ref('')

const monthsOptions = [
  { label: '一月', value: '1' },
  { label: '二月', value: '2' },
  { label: '三月', value: '3' },
  { label: '四月', value: '4' },
  { label: '五月', value: '5' },
  { label: '六月', value: '6' },
  { label: '七月', value: '7' },
  { label: '八月', value: '8' },
  { label: '九月', value: '9' },
  { label: '十月', value: '10' },
  { label: '十一月', value: '11' },
  { label: '十二月', value: '12' }
];

// 资质信息
const qualificationEffectiveTime = ref('')
const qualificationExpirationTime = ref('')

// 其他信息
const precautions = ref('')

const fillForm = (permitData) => {
  if (!permitData) return;
  productName.value = permitData.productName || '';
  productCategory.value = permitData.productCategory || '';
  variety.value = permitData.variety || '';
  plantingCycle.value = permitData.plantingCycle || 90;
  description.value = permitData.description || '';
  suitableLand.value = permitData.suitableLand || '';
  
  // 处理 suitableTemperature 字符串 "15-25°C" 为数组 [15, 25]
  if (permitData.suitableTemperature) {
    const tempMatch = permitData.suitableTemperature.match(/(\d+)-(\d+)°C/);
    if (tempMatch && tempMatch.length === 3) {
      suitableTemperature.value = [parseInt(tempMatch[1]), parseInt(tempMatch[2])];
    }
  }

  // 处理 suitableMonths 字符串 "一月,二月" 为数组 ["1", "2"]
  if (permitData.suitableMonths) {
    const monthsLabels = permitData.suitableMonths.split(',');
    suitableMonths.value = monthsLabels.map(label => {
      const monthOption = monthsOptions.find(opt => opt.label === label);
      return monthOption ? monthOption.value : '';
    }).filter(value => value !== '');
  }

  plantingRecordNumber.value = permitData.plantingRecordNumber || '';
  qualificationEffectiveTime.value = permitData.qualificationEffectiveTime || '';
  qualificationExpirationTime.value = permitData.qualificationExpirationTime || '';
  precautions.value = permitData.precautions || '';
};

onMounted(() => {
  fillForm(props.initialPermitData);
});

watch(() => props.initialPermitData, (newVal) => {
  fillForm(newVal);
}, { immediate: true });

const validateForm = () => {
  if (!productName.value) {
    ElMessage.error('产品名称不能为空');
    return false;
  }
  if (!productCategory.value) {
    ElMessage.error('产品类别不能为空');
    return false;
  }
  if (!variety.value) {
    ElMessage.error('品种不能为空');
    return false;
  }
  if (plantingCycle.value === undefined || plantingCycle.value === null) {
    ElMessage.error('种植周期不能为空');
    return false;
  }
  if (!suitableLand.value) {
    ElMessage.error('适宜土地类型不能为空');
    return false;
  }
  if (!suitableTemperature.value || suitableTemperature.value.length !== 2 || suitableTemperature.value[0] === undefined || suitableTemperature.value[1] === undefined) {
    ElMessage.error('适宜温度范围不能为空或不完整');
    return false;
  }
  if (!suitableMonths.value || suitableMonths.value.length === 0) {
    ElMessage.error('适宜种植月份不能为空');
    return false;
  }
  return true;
};

// 保存方法
const savemsg = async () => {
  if (!validateForm()) {
    return;
  }
  try {
    // 构建请求数据
    const permitData = {
      productName: productName.value,
      productCategory: productCategory.value,
      variety: variety.value,
      plantingCycle: plantingCycle.value,
      description: description.value,
      suitableLand: suitableLand.value,
      suitableTemperature: `${suitableTemperature.value[0]}-${suitableTemperature.value[1]}°C`,
      suitableMonths: suitableMonths.value.map(month => monthsOptions.find(opt => opt.value === month)?.label).join(','),
      plantingRecordNumber: plantingRecordNumber.value,
      qualificationEffectiveTime: qualificationEffectiveTime.value,
      qualificationExpirationTime: qualificationExpirationTime.value,
      precautions: precautions.value,
      userId: userId,
      auditStatus:'待审核'
    }

    // 调用新增准许种植产品管理接口
    const response = await addPermit(permitData)

    console.log('成功:', response)

    // 显示成功消息
    ElMessage.success('提交成功，等待审核')

  } catch (error) {
    console.error('保存失败:', error)
    // 显示错误消息
    ElMessage.error('审核失败: ' + (error.message || '未知错误'))
  }
}
</script>

<style scoped>
.crop-form-container {
  margin: 20px auto;
  padding: 20px;
  border-radius: 20px;
  background-color: #fff;
  box-shadow: rgba(209, 209, 209, 0.438) 5px 5px 10px;
}

.section-header {
  margin: 30px 0 20px 0;
  padding-bottom: 10px;
  border-bottom: 2px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-header h3 {
  font-size: 24px;
  color: #303133;
  font-weight: 600;
  margin: 0;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.form-item {
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: start;
}

.form-grid .form-item {
  margin-bottom: 0;
}

.form-label {
  font-size: 18px;
  display: inline-block;
  text-align: left;
  margin-bottom: 8px;
  color: #606266;
  font-weight: 500;
}

.required {
  color: #f13939;
}

.form-input {
  font-size: 16px;
  outline: none;
  color: #000;
  background-color: #ffffff;
  border: 2px solid #dcdfe6;
  border-radius: 8px;
  width: 100%;
  padding: 12px 15px;
  height: 45px;
  transition: border-color 0.3s;
  box-sizing: border-box;
}

.form-input:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.form-select {
  font-size: 16px;
  outline: none;
  color: #000;
  background-color: #ffffff;
  border-radius: 8px;
  width: 100%;
  padding: 12px 15px;
  height: 45px;
  transition: border-color 0.3s;
  box-sizing: border-box;
  cursor: pointer;
}

.form-select:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.fixed-textarea {
  width: 100%;
  height: 120px;
  resize: none;
  padding: 12px 15px;
  font-size: 16px;
  border: 2px solid #dcdfe6;
  border-radius: 8px;
  box-sizing: border-box;
  outline: none;
  color: #000;
  background-color: #fff;
  transition: border-color 0.3s;
  font-family: inherit;
}

.fixed-textarea:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.form-footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 30px;
    padding: 0 20px;
    gap: 15px;
  }

  .temperature-preview,
  .month-preview,
  .planting-cycle-preview {
    margin-top: 10px; /* 添加顶部外边距 */
    font-size: 14px;
    color: #2e7d32; /* 改为绿色 */
  }

  /* 自定义滑块组件为绿色 */
  .el-slider__bar {
    background-color: #2e7d32;
  }
  .el-slider__button {
    border-color: #2e7d32;
    background-color: #fff;
  }
  .el-slider__button:hover,
  .el-slider__button:focus {
    border-color: #2e7d32;
    background-color: #2e7d32;
  }

  /* 响应式设计 */
@media (max-width: 768px) {
  .form-grid {
    grid-template-columns: 1fr;
  }
  
  .section-header h3 {
    font-size: 20px;
  }
  
  .form-label {
    font-size: 16px;
  }
}
</style>